package com.costaccounting.web.controller.feesys;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.costaccounting.base.domain.ZsCategory;
import com.costaccounting.base.domain.ZsItem;
import com.costaccounting.base.domain.ZsItemCategoryConfig;
import com.costaccounting.base.service.IZsCategoryPersonConfigService;
import com.costaccounting.base.service.IZsCategoryService;
import com.costaccounting.base.service.IZsItemCategoryConfigService;
import com.costaccounting.base.service.IZsItemService;
import com.costaccounting.common.constant.UserConstants;
import com.costaccounting.common.core.domain.TreeSelect;
import com.costaccounting.common.core.domain.entity.SysDictData;
import com.costaccounting.common.utils.SecurityUtils;
import com.costaccounting.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.costaccounting.common.annotation.Log;
import com.costaccounting.common.core.controller.BaseController;
import com.costaccounting.common.core.domain.AjaxResult;
import com.costaccounting.common.enums.BusinessType;
import com.costaccounting.feesys.domain.ZsFee;
import com.costaccounting.feesys.service.IZsFeeService;
import com.costaccounting.common.utils.poi.ExcelUtil;
import com.costaccounting.common.core.page.TableDataInfo;

/**
 * 费用管理Controller
 * 
 * @author ruoyi
 * @date 2021-11-08
 */
@RestController
@RequestMapping("/feesys/feeinfo")
public class ZsFeeController extends BaseController
{
    @Autowired
    private IZsFeeService zsFeeService;
    @Autowired
    private IZsItemService itemService;
    @Autowired
    private IZsCategoryService categoryService;
    @Autowired
    private IZsCategoryPersonConfigService configService;
    @Autowired
    private IZsItemCategoryConfigService itemCategoryConfigService;


    /**
     * 查询费用管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ZsFee zsFee)
    {
        startPage();
        if(zsFee.getCategoryId()!=null){
            zsFee.setAncestors(zsFee.getCategoryId()+"");
            zsFee.setCategoryId(null);
        }
        List<ZsFee> list = zsFeeService.selectZsFeeList(zsFee);
        return getDataTable(list);
    }
    @GetMapping(value ="/selectZsFeeReport")
    public AjaxResult selectZsFeeReport(ZsFee zsFee){
        ZsCategory category1 = categoryService.selectZsCategoryById(zsFee.getCategoryId());
        Long categoryId=category1.getId();
        String categoryName=category1.getName();
        List<Long> categoryIds=getCategoryIdList(categoryId);
        zsFee.setCategoryIdList(categoryIds);
        zsFee.setCategoryId(null);
        List<ZsFee> list = zsFeeService.selectZsFeeReport(zsFee);
        //取占比，需要先取出父节点的总造价，然后当前节点的三项费用除以父节点的费用，就是占比
        Long pid = category1.getPid();
        //如果pid为0，表示当前节点就是一级节点，占比就是100%
        boolean isFirstCategory=false;
        Map<String, ZsFee> map=new HashMap<>();
        if(pid.equals(0L)){
            isFirstCategory=true;
        }else{
            List<Long> pcategoryIds=getCategoryIdList(pid);
            ZsFee pfee=new ZsFee();
            pfee.setCategoryIdList(pcategoryIds);
            pfee.setCategoryId(null);
            List<ZsFee> plist = zsFeeService.selectZsFeeReport(pfee);
            if(StringUtils.isNotEmpty(plist)){
                map = plist.stream().collect(Collectors.toMap(ZsFee::getFeeType, a -> a));
            }
        }

        if(StringUtils.isNotEmpty(list)){
            //取出项目的总面积
            ZsItemCategoryConfig itemCategoryConfig=new ZsItemCategoryConfig();
            itemCategoryConfig.setItemId(zsFee.getItemId());
            if(StringUtils.isNotEmpty(zsFee.getFloorId())){
                itemCategoryConfig.setCategoryId(Long.parseLong(zsFee.getFloorId()));
            }
            List<ZsItemCategoryConfig> zsItemCategoryConfigs = itemCategoryConfigService.selectZsItemCategoryConfigList(itemCategoryConfig);
            BigDecimal area=new BigDecimal(1);
            if(StringUtils.isNotEmpty(zsItemCategoryConfigs)){
                area = zsItemCategoryConfigs.stream().map(ZsItemCategoryConfig::getArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(area.compareTo(new BigDecimal(0))==0){
                    area=new BigDecimal(1);
                }
            }
            for (ZsFee f : list) {
                f.setCategoryId(categoryId);
                f.setCategoryName(categoryName);
                if(!"2".equals(f.getFeeType())){
                    f.setYsTotal(getDecimal(f.getLaborTotal()).add(getDecimal(f.getMaterialTotal())).add(getDecimal(f.getMachineryTotal())));
                    f.setYsNum(getDecimal(f.getLaborNum()).add(getDecimal(f.getMaterialNum())).add(getDecimal(f.getMachineryNum())));
                    if(f.getYsNum().compareTo(new BigDecimal(0))==0){
                        f.setYsPrice(new BigDecimal(0));
                    }else{
                        f.setYsPrice((getDecimal(f.getYsTotal()).divide(getDecimal(f.getYsNum()),2,BigDecimal.ROUND_HALF_UP)));
                    }
                }
                //取单方报价总面积/总价格
                f.setAvgPrice(((getDecimal(f.getYsTotal()).divide(getDecimal(area),2,BigDecimal.ROUND_HALF_UP))));
                //占比
                //如果是一级目录，占比为100%
                if(isFirstCategory){
                    f.setZhaibi("100%");
                }else{
                    if(map.containsKey(f.getFeeType())){
                        ZsFee zsFee1 = map.get(f.getFeeType());
                        BigDecimal total=new BigDecimal(0);
                        total=total.add(getDecimal(zsFee1.getLaborTotal())).add(getDecimal(zsFee1.getMachineryTotal())).add(getDecimal(zsFee1.getMaterialTotal()));
                        if(total!=null&&total.compareTo(new BigDecimal(0))!=0){
                            f.setZhaibi((getDecimal((f.getYsTotal()).divide(total,2,BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(100))).toString()+"%");
                        }
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }

    List<Long> getCategoryIdList(Long categoryId){
        ZsCategory category=new ZsCategory();
        category.setAncestors(categoryId+"");
        List<ZsCategory> zsCategories = categoryService.selectZsCategoryList(category);
        List<Long> categoryIds=new ArrayList<>();
        if(StringUtils.isNotEmpty(zsCategories)){
            categoryIds=zsCategories.stream().map(ZsCategory::getId).collect(Collectors.toList());
        }
        return categoryIds;
    }


    BigDecimal getDecimal(BigDecimal num){
        if(num==null){
            return new BigDecimal(0);
        }else{
            return num;
        }
    }

    /**
     * 导出费用管理列表
     */
    @PreAuthorize("@ss.hasPermi('feesys:feeinfo:export')")
    @Log(title = "费用管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ZsFee zsFee)
    {
        List<ZsFee> list = zsFeeService.selectZsFeeList(zsFee);
        ExcelUtil<ZsFee> util = new ExcelUtil<ZsFee>(ZsFee.class);
        return util.exportExcel(list, "费用管理数据");
    }

    /**
     * 获取费用管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('feesys:feeinfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(zsFeeService.selectZsFeeById(id));
    }

    /**
     * 新增费用管理
     */
    @PreAuthorize("@ss.hasPermi('feesys:feeinfo:add')")
    @Log(title = "费用管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZsFee zsFee)
    {
        return toAjax(zsFeeService.insertZsFee(zsFee));
    }

    /**
     * 修改费用管理
     */
    @PreAuthorize("@ss.hasPermi('feesys:feeinfo:edit')")
    @Log(title = "费用管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZsFee zsFee)
    {
        return toAjax(zsFeeService.updateZsFee(zsFee));
    }

    /**
     * 删除费用管理
     */
    @PreAuthorize("@ss.hasPermi('feesys:feeinfo:remove')")
    @Log(title = "费用管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(zsFeeService.deleteZsFeeByIds(ids));
    }

    @PostMapping(value = "/getCategoryTreeselect")
    public AjaxResult getCategoryTreeselect(ZsItem zsItem) {
        List<TreeSelect> categoryTreeselect = zsFeeService.getCategoryTreeselect(zsItem);
        return AjaxResult.success(categoryTreeselect);
    }

    /**
     * 获取当前项目的楼号
     * @return
     */
    @PostMapping(value = "/getFloorList")
    public AjaxResult getFloorList(ZsFee zsFee) {
        List<SysDictData> floorList = zsFeeService.getFloorList(zsFee);
        return AjaxResult.success(floorList);
    }

    /**
     * 获取当前登录用户正在操作的项目
     * @return
     */
    @PostMapping(value = "/getItem")
    public AjaxResult getItem() {
        ZsItem activeItem = zsFeeService.getActiveItem();
        if(activeItem!=null){
            return AjaxResult.success(activeItem);
        }else{
            return AjaxResult.error("当前用户没有进行中的项目");
        }
    }

    /**
     * 报表页，获取有权限的所有项目
     * @return
     */
    @PostMapping(value = "/getItemList")
    public AjaxResult getItemList() {
        List<ZsItem> itemList = zsFeeService.getItemList();
        return AjaxResult.success(itemList);
    }

    @GetMapping(value ="/selectCostReport")
    public AjaxResult selectCostReport(ZsFee zsFee){
        List<ZsFee> zsFees = zsFeeService.selectCostReport(zsFee);
        return AjaxResult.success(zsFees);
    }

    @GetMapping(value ="/selectWarnReport")
    public AjaxResult selectWarnReport(ZsFee zsFee){
        List<ZsFee> zsFees = zsFeeService.selectWarnReport(zsFee);
        return AjaxResult.success(zsFees);
    }
}
